﻿using System;
using System.IO;


namespace CSP.CRM.Deployer
{

  class Program
  {
    static int languageCode;
    static string organizationName = null;
    static string logFileName = null;
    static Uri crmServerUri;
    static string crmLoginUser;

    static void Main(string[] args)
    {
      try
      {
        ParseArguments(args);
        if ((organizationName == null) || (crmServerUri == null) || (crmLoginUser == null))
        {
          Console.Error.WriteLine("Use: csp.crmdeployer.exe -s CrmServerUrl -o OrganizationName -u CrmUser [-l logfile]");
          return;
        }

        TextWriter log = Console.Out;
        if (logFileName != null)
          log = File.CreateText(Directory.GetCurrentDirectory() + "\\" + logFileName);

        log.WriteLine("CSP Deployment Version 0.3 starting at {0}", DateTime.Now.ToLongTimeString());
        CspCrmDeployer deploy = new CspCrmDeployer(crmServerUri, organizationName, crmLoginUser, Console.Out);

        ////DASB 16/01/2009 LanguageCode is stored in the config file
        deploy.LanguageCode = languageCode;

        deploy.Run();
        log.WriteLine("CSP Deployment finished at {0}", DateTime.Now.ToLongTimeString());
        log.Close();
      }
      catch (System.Web.Services.Protocols.SoapException soapEx)
      {
        Console.Error.WriteLine(soapEx.Detail.OuterXml);
      }
      catch (Exception ex)
      {
        Console.Error.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
      }

    }

    static void ParseArguments(string[] args)
    {
      //// DASB 16/01/2009 LanguageCode is now stored in the .config file
      languageCode = Settings.Default.LanguageCode;

      for (int i = 0; i < args.Length; i++)
      {
        if (args[i].ToLower() == "-o")
        {
          if (args.Length >= i)
            organizationName = args[i + 1];
        }
        if (args[i].ToLower() == "-l")
        {
          if (args.Length >= i)
            logFileName = args[i + 1];
        }
        if (args[i].ToLower() == "-s")
        {
          if (args.Length >= i)
            crmServerUri = new Uri(args[i + 1]);
        }

        if (args[i].ToLower() == "-u")
        {
          if (args.Length >= i)
            crmLoginUser = args[i + 1];
        }

        //// DASB 16/01/2009 LanguageCode is now stored in the .config file
        //if (args[i].ToLower() == "-lc")
        //{
        //  if (args.Length >= i)
        //    languageCode = Int32.Parse(args[i + 1]);
        //}

      }
    }
  }
}
